package cn.com.do1.component.merchandise.merchandise.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.exception.IllegalParameterException;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.component.merchandise.merchandise.model.*;
import cn.com.do1.component.merchandise.merchandise.service.IMerchandiseService;
import cn.com.do1.component.merchandise.merchandise.vo.TbCzMerchandiseVO;
import cn.com.do1.component.merchant.merchant.model.TbCzMerchantPO;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantListVO;
import cn.com.do1.component.systemmgr.user.model.User;
import cn.com.do1.component.util.ExcelUtil;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import cn.com.do1.common.util.AssertUtil;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.common.util.reflation.BeanHelper;
import cn.com.do1.common.util.reflation.ClassTypeUtil;
import cn.com.do1.dqdp.core.DqdpAppContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Role;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司 All rights reserved. User: ${user}
 */
public class MerchandiseAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(MerchandiseAction.class);
    private IMerchandiseService merchandiseService;
    private TbCzMerchandisePO tbCzMerchandisePO;
    private String ids[];
    private String id;
    private String status;

    public IMerchandiseService getMerchandiseService() {
        return merchandiseService;
    }

    @Resource
    public void setMerchandiseService(IMerchandiseService merchandiseService) {
        this.merchandiseService = merchandiseService;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "merMoney", type = "number"),
            @SearchValueType(name = "merName", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("merchandiseList")
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = merchandiseService.searchMerchandise(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        // todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        // todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        // 完成批量更新的代码
    }

    public void setTbCzMerchandisePO(TbCzMerchandisePO tbCzMerchandisePO) {
        this.tbCzMerchandisePO = tbCzMerchandisePO;
    }

    public TbCzMerchandisePO setTbCzMerchandisePO() {
        return this.tbCzMerchandisePO;
    }

    @ActionRoles("merchandiseAdd")
    public void addTbCzMerchandisePO() {
        tbCzMerchandisePO.setMerInsert(new Date());
        User user = (User) DqdpAppContext.getCurrentUser();
        tbCzMerchandisePO.setMerOper(user.getUsername());
        try {
            this.merchandiseService.insertPO(tbCzMerchandisePO, true);
            setActionResult("0", "新增套餐成功");
        } catch (Exception e) {
            setActionResult("1002", "新增套餐失败");
            logger.error(e.getMessage(), e);
        } catch (BaseException e) {
            setActionResult("1002", "新增套餐失败");
            logger.error(e.getMessage(), e);
        }
        doJsonOut();
    }

    @ActionRoles("merchandiseEdit")
    public void updateTbCzMerchandisePO() {
        tbCzMerchandisePO.setMerUpdate(new Date());
        User user = (User) DqdpAppContext.getCurrentUser();

        tbCzMerchandisePO.setMerOper(user.getUsername());
        try {
            this.merchandiseService.updatePO(tbCzMerchandisePO, false);
            setActionResult("0", "更新成功");
        } catch (Exception e) {
            setActionResult("1002", "更新失败");
            logger.error(e.getMessage(), e);
        }
        doJsonOut();
    }

    public void deleteTbCzMerchandisePO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbCzMerchandisePO._setPKValue(id);
        super.ajaxDelete(tbCzMerchandisePO);
    }

    public void batchDeleteTbCzMerchandisePO() {
        super.ajaxBatchDelete(TbCzMerchandisePO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("merchandiseView")
    public void ajaxView() throws Exception, BaseException {
        TbCzMerchandisePO xxPO = merchandiseService.searchByPk(TbCzMerchandisePO.class, id);

        TbCzMerchandiseVO tbCzMerchandisePO = ClassTypeUtil.getAutoReplaceBeanInstance(TbCzMerchandiseVO.class);
        BeanHelper.copyFormatProperties(tbCzMerchandisePO, xxPO, false);
        addJsonFormateObj("tbCzMerchandisePO", tbCzMerchandisePO);
        // addJsonFormateObj("tbCzMerchandisePO", xxPO);//
        // 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    public TbCzMerchandisePO getTbCzMerchandisePO() {
        return this.tbCzMerchandisePO;
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "操作成功", faileMsg = "操作失败"))
    public void updateStatus() throws Exception, BaseException {
        this.merchandiseService.updateStatus(id, status);
    }

    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "merMoney", type = "number"),
            @SearchValueType(name = "merName", type = "string", format = "%%%s%%")})
    @ActionRoles("merchandiseExport")
    public String export() {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);

        List<TbCzMerchandiseVO> list = null;
        try {
            pager = merchandiseService.searchMerchandise(getSearchValue(), pager);
            list = (List<TbCzMerchandiseVO>) pager.getPageData();

        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
        } finally {
        }

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head = {"套餐名称", "套餐价格", "套餐排序", "套餐状态", "新增时间", "更新时间", "操作人"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbCzMerchandiseVO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "套餐信息" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }
}
